package com.moli.iov.base.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moli.iov.base.cache.redis.VehicleAttentionCacheService;
import com.moli.iov.base.cache.redis.VehicleFollowGroupCacheService;
import com.moli.iov.base.enums.YesOrNoEnum;
import com.moli.iov.base.model.VehicleAttentionParam;
import com.moli.iov.base.model.dto.req.VehicleAttentionReqDto;
import com.moli.iov.base.model.po.VehicleAttention;
import com.moli.iov.base.service.IVehicleAttentionService;
import com.moli.iov.base.util.CollectionUtils;
import com.moli.iov.exception.BusinessException;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.base.mapper.VehicleAttentionMapper;

import java.util.*;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 车辆关注表  服务实现类
 * </p>
 *
 * @author whl
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class VehicleAttentionServiceImpl extends
        ServiceImpl<VehicleAttentionMapper, VehicleAttention> implements IVehicleAttentionService {

    @Autowired
    private VehicleAttentionCacheService vehicleAttentionCacheService;

    @Autowired
    private VehicleFollowGroupCacheService vehicleFollowGroupCacheService;


    @Override
    public RestResponse saveVehicleAttention(VehicleAttentionReqDto vehicleAttentionReqDto) {
        log.info("车辆监控-车辆管理-添加关注入参VehicleAttentionReqDto:{}" + vehicleAttentionReqDto);
        if (vehicleAttentionReqDto == null) {
            return RestResponse.failure("参数为空");
        }
        VehicleAttention vehicleAttention = new VehicleAttention();
        BeanUtils.copyProperties(vehicleAttentionReqDto, vehicleAttention);
        boolean save = this.save(vehicleAttention);
        if (save) {
            vehicleAttentionCacheService.setVehicleAttention(vehicleAttention);
            return RestResponse.success("操作成功");
        } else {
            return RestResponse.failure("添加失败");
        }
    }


    @Override
    public RestResponse updateVehicleAttention(VehicleAttentionReqDto vehicleAttentionReqDto) {
        log.info("车辆监控-车辆管理-修改关注入参VehicleAttentionReqDto:{}" + vehicleAttentionReqDto);
        if (vehicleAttentionReqDto == null) {
            return RestResponse.failure("参数为空");
        }
        //淘汰缓存
        vehicleAttentionCacheService.deleteVehicleAttention(vehicleAttentionReqDto.getUserId(), vehicleAttentionReqDto.getGroupId(), vehicleAttentionReqDto.getVin());

        VehicleAttention vehicleAttention = new VehicleAttention();
        CommonUtils.copyProperties(vehicleAttentionReqDto, vehicleAttention);
        boolean save = this.saveOrUpdate(vehicleAttention);
        if (save) {
            if (vehicleAttention.getIsDelete().intValue() == YesOrNoEnum.NO.getCode()) {
                vehicleAttentionCacheService.setVehicleAttention(vehicleAttention);
            }
            return RestResponse.success();
        } else {
            return RestResponse.failure("添加失败");
        }
    }

    @Override
    public Set<String> findByUserIdAndGroupId(Long userId, Long groupId) {
        Set<String> set = vehicleAttentionCacheService.getVehicleAttentionByUserIdAndGroupId(userId, groupId);
        if (set != null && !set.isEmpty()) {
            return set;
        } else {
            VehicleAttentionParam vehicleAttentionParam = new VehicleAttentionParam();
            vehicleAttentionParam.queryEqUserId(userId);
            vehicleAttentionParam.queryEqGroupId(groupId);
            List<VehicleAttention> list = this.list(vehicleAttentionParam.get());
            if (list != null && !list.isEmpty()) {
                Set<String> collect = list.stream().map(VehicleAttention::getVin)
                        .collect(Collectors.toSet());
                vehicleAttentionCacheService.setVehicleAttentions(collect, userId, groupId);
                return collect;
            }
            return null;
        }

    }

    @Override
    public VehicleAttention getVehicleAttentionByVin(String vin, Long userId, Long groupId) {
        VehicleAttentionParam vehicleAttentionParam = new VehicleAttentionParam();
        vehicleAttentionParam.queryEqUserId(userId);
        vehicleAttentionParam.queryEqGroupId(groupId);
        vehicleAttentionParam.queryEqVin(vin);
        return this.getOne(vehicleAttentionParam.get(), false);
    }

    @Override
    public void saveBatchVehicleAttention(List<VehicleAttention> list, Long userId, Long groupId) {
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException("参数为空");
        }

        Set<String> set = vehicleAttentionCacheService.getVehicleAttentionByUserIdAndGroupId(userId, groupId);
        List<VehicleAttention> saveList = new ArrayList<>();
        for (VehicleAttention vehicleAttention : list) {
            if (set != null && set.size() > 0) {
                if (vehicleAttention != null && !set.contains(vehicleAttention.getVin())) {
                    saveList.add(vehicleAttention);
                }
            } else {
                saveList.add(vehicleAttention);
            }
        }

        if (saveList.size() > 0) {
            boolean b = saveBatch(saveList);
            if (b) {
                Set<String> collect = saveList.stream().map(VehicleAttention::getVin)
                        .collect(Collectors.toSet());
                vehicleAttentionCacheService.setVehicleAttentions(collect, userId, groupId);
                this.setVehicleFollowGroupCache(saveList,userId,groupId);
            }
        }
    }

    void setVehicleFollowGroupCache(List<VehicleAttention> list, Long userId, Long groupId){
        log.info("关注组缓存添加");
        Set<String> set = vehicleFollowGroupCacheService.findByUserIdAndGroupId(userId, groupId);
        if(set==null){
            set = new HashSet<>();
        }

        for (VehicleAttention vehicleAttention : list) {
            set.add(vehicleAttention.getVin());
            log.info("关注组缓存添加 >>>>>> 待添加车架号：{}",vehicleAttention.getVin());
        }
        log.info("关注组缓存添加 >>>>>> userId:{},groupId{},set:{}",userId,groupId,set);
        vehicleFollowGroupCacheService.set(groupId,userId,set);

    }

    @Override
    public void initVehicleAttention() {
        //清空缓存
        vehicleAttentionCacheService.cleanVehicleAttentionCache();
        VehicleAttentionParam param = new VehicleAttentionParam();
        List<VehicleAttention> list = list(param.get());
        if (!CollectionUtils.isEmpty(list)) {
            Map<Long, Map<Long, List<VehicleAttention>>> collect = list.stream()
                    .collect(Collectors.groupingBy(VehicleAttention::getUserId, Collectors.groupingBy(VehicleAttention::getGroupId)));
            collect.forEach(
                    (userId, followGroups) ->
                            followGroups.forEach((groupId, vehicleAttentions) ->
                                    vehicleAttentionCacheService.setVehicleAttentions(vehicleAttentions.stream().map(VehicleAttention::getVin).collect(Collectors.toSet()), userId, groupId)
                            )
            );
        }
    }

    @Override
    public void deleteBatchVehicleAttention(List<VehicleAttention> list, Long sysUserId, Long groupId) {
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException("参数为空");
        }
        boolean b = saveOrUpdateBatch(list);
        if (b) {
            Set<String> collect = list.stream().map(VehicleAttention::getVin)
                    .collect(Collectors.toSet());
            vehicleAttentionCacheService.deleteVehicleAttention(collect, sysUserId, groupId);
            vehicleFollowGroupCacheService.deleteValue(collect,sysUserId,groupId);
        }
    }

    @Override
    public List<VehicleAttention> listVehicleAttentionByVin(List<String> vinList, Long userId, Long groupId) {
        if (CollectionUtils.isEmpty(vinList)) {
            throw new BusinessException("vinList不能为空");
        }
        VehicleAttentionParam vehicleAttentionParam = new VehicleAttentionParam();
        vehicleAttentionParam.queryEqUserId(userId);
        vehicleAttentionParam.queryEqGroupId(groupId);
        vehicleAttentionParam.queryInVin(vinList);
        return list(vehicleAttentionParam.get());
    }

    @Override
    public boolean removeByUserIdAndGroupId(Long userId, Long groupId) {
        VehicleAttentionParam vehicleAttentionParam = new VehicleAttentionParam();
        vehicleAttentionParam.queryEqUserId(userId);
        vehicleAttentionParam.queryEqGroupId(groupId);
        return remove(vehicleAttentionParam.get());
    }

}
